﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WarOfDev.EF;
using WarOfDev.Core;
using WarOfDev.Core.Common;
using WarOfDev.Core.Configuration;

namespace WarOfDev.Web.Controllers
{
    public class PuzzleController : BaseController
    {
        private WarDevEntities db = new WarDevEntities();

        //
        // GET: /Puzzle/
        public ActionResult Index()
        {
            ViewBag.currentDeveloperId = this.CurrentUser.Id;
            return View(db.Posts.Include("Developer").Where(p=>p.PostType==(int)EnumPostType.Puzzle).ToList());
        }

        //
        // GET: /Puzzle/Details/5

        public ActionResult Details(string id = null)
        {
            ViewBag.currentDeveloperId = this.CurrentUser.Id;
            Post post = db.Posts.Include("Comments").Include("Comments.Developer").Single(p => p.Id == id);
            if (post == null)
            {
                return HttpNotFound();
            }
            return View(post);
        }

        //
        // GET: /Puzzle/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Puzzle/Create

        [HttpPost]
        public ActionResult Create(Post post)
        {
            if (ModelState.IsValid)
            {
                post.Id = Guid.NewGuid().ToString();

                post.CreatedOn = post.ModifiedOn = DateTime.Now;
                post.CreatedBy = post.ModifiedBy = this.CurrentUser.Id;
                post.PostType = (int)EnumPostType.Puzzle;

                var tags = post.Tags.Split(',');
                var oldTags = from tag in db.Tags
                              where tags.Contains(tag.TagName)
                              select tag.TagName;

                var newTags = tags.Except(oldTags);
                newTags.ToList().ForEach(t =>
                    db.Tags.AddObject(new Tag() { 
                        TagName=t,
                        CreateOn=DateTime.Now,
                        CreateBy=this.CurrentUser.Id
                    })
                );

                var tagClouds = new List<TagCloud>();
                foreach (string tag in tags)
                {
                    tagClouds.Add(new TagCloud
                    {
                        Id = Guid.NewGuid().ToString(),
                        PostId = post.Id,
                        CreatedBy = this.CurrentUser.Id,
                        CreatedOn = DateTime.Now,
                        TagName = tag
                    });
                }

                var link = new MessageLink
                {
                    Id=Guid.NewGuid().ToString(),
                    LinkText=post.Title,
                    LinkHref= Url.Action("Details", "Puzzle", new { id = post.Id }),
                    CreatedBy=this.CurrentUser.Id,
                    CreatedOn=DateTime.Now
                };

                var message = new Message { 
                    Id=Guid.NewGuid().ToString(),
                    CreatedBy=this.CurrentUser.Id,
                    CreatedOn=DateTime.Now,
                    MessageContent= string.Format("{0} posted a puzzle, help him(her) to resolve it :) ",
                           this.CurrentUser.NickName)
                };

                message.Links.Add(link);
                tagClouds.ForEach(t => db.TagClouds.AddObject(t));
                db.Messages.AddObject(message);
                db.Posts.AddObject(post);
                db.SaveChanges();

                return RedirectToAction("Index");
            }

            return View(post);
        }


        public ActionResult PickAnswer(string postId, string CommentId,int rewardType)
        {

            var post= db.Posts.Single(p=>p.Id==postId);
            var comment=db.Comments.Single(c=>c.Id==CommentId);
           
            //change post's status
            post.Status = rewardType == (int)EnumPuzzleRewardType.ByExperienceValue ?(int)EnumPostStatus.Closed :(int)EnumPostStatus.Rewarding;
            post.ModifiedBy = this.CurrentUser.Id;
            post.ModifiedOn = DateTime.Now;
            post.PickedCommentId = CommentId;

            //change comment's status
            comment.Status = post.Status == (int)EnumPostStatus.Closed ? (int)EnumCommentStatus.Closed : (int)EnumCommentStatus.Rewarding;
            comment.ModifiedBy = this.CurrentUser.Id;
            comment.ModifiedOn = DateTime.Now;

            //change comment's owner's experience value
            var developer = db.Developers.Single(d => d.Id == comment.CreateBy);
            developer.ExperienceValue += post.ExperienceValue??0;
            developer.ModifiedBy = developer.Id;
            developer.ModifiedOn = DateTime.Now;

            if (rewardType == (int)EnumPuzzleRewardType.ByExperienceValue)
            {
                //subtract puzzle's owner's experience value
                var puzzleOnwer = db.Developers.Single(d => d.Id == post.CreatedBy);
                puzzleOnwer.ExperienceValue -= post.ExperienceValue??0;

                var minusHistory = new ExperienceValueHistory { 
                    Id=Guid.NewGuid().ToString(),
                    ChangedExperienceValue= -post.ExperienceValue,
                    CreatedBy=this.CurrentUser.Id,
                    CreatedOn=DateTime.Now,
                    DeveloperId=puzzleOnwer.Id,
                    FromAction=(int)EnumChangeExperienceValueAction.SubstractedFromPuzzle
                };

                db.ExperienceValueHistorys.AddObject(minusHistory);
            }

            // add history for adding experience value to comment's owner
            var history = new ExperienceValueHistory { 
                Id=Guid.NewGuid().ToString(),
                ChangedExperienceValue=post.ExperienceValue,
                CreatedBy=this.CurrentUser.Id,
                CreatedOn=DateTime.Now,
                DeveloperId=comment.CreateBy,
                FromAction=(int)EnumChangeExperienceValueAction.RewardedByPuzzerOnwer
            };

            db.ExperienceValueHistorys.AddObject(history);
            db.SaveChanges();
            return RedirectToAction("Index", new { id=postId });
        }

        public ActionResult ReceiveReward(string commentId)
        {
            var comment = db.Comments.Include("Post").Single(c => c.Id == commentId);
            
            comment.Status = (int)EnumCommentStatus.Closed;
            comment.ModifiedBy = this.CurrentUser.Id;
            comment.ModifiedOn = DateTime.Now;

            var onwer = db.Developers.Single(d => d.Id == comment.CreateBy);
            onwer.ExperienceValue += comment.Post.ExperienceValue??0;
            onwer.ModifiedOn = DateTime.Now;
            onwer.ModifiedBy = this.CurrentUser.Id;

            var history = new ExperienceValueHistory { 
                Id=Guid.NewGuid().ToString(),
                ChangedExperienceValue=comment.Post.ExperienceValue,
                CreatedBy=this.CurrentUser.Id,
                CreatedOn=DateTime.Now,
                DeveloperId=onwer.CreatedBy,
                FromAction=(int) EnumChangeExperienceValueAction.RewardedByPuzzerOnwer
            };

            db.ExperienceValueHistorys.AddObject(history);
            db.SaveChanges();

            return RedirectToAction("Details", new { comment.Post.Id });
        }

        public ActionResult Anwser(string puzzleId,string anwser)
        {
            if(!string.IsNullOrEmpty(puzzleId) &&  !string.IsNullOrEmpty(anwser))
            {
                Comment comment = new Comment
                {
                    Id = Guid.NewGuid().ToString(),
                    PostId = puzzleId,
                    CommendType = (int)EnumPostType.Puzzle,
                    CreateOn = DateTime.Now,
                    ModifiedOn = DateTime.Now,
                    CreateBy = this.CurrentUser.Id,
                    ModifiedBy = this.CurrentUser.Id,
                    ExperienceValue=(int)DefaultExperienceValueSetting.AddCommentToPuzzle,
                    Commend = anwser
                };

                db.Comments.AddObject(comment);

                // add default experience value to developer adding commend
                var commender = db.Developers.Single(d => d.Id == this.CurrentUser.Id);
                commender.ExperienceValue += DefaultExperienceValueSetting.AddCommentToPuzzle;
                commender.ModifiedBy = commender.Id;
                commender.ModifiedOn = DateTime.Now;
                db.ObjectStateManager.ChangeObjectState(commender, EntityState.Modified);

                // add experience value history
                ExperienceValueHistory history = new ExperienceValueHistory { 
                    CreatedBy=this.CurrentUser.Id,
                    CreatedOn=DateTime.Now,
                    DeveloperId=this.CurrentUser.Id,
                    Id=Guid.NewGuid().ToString(),
                    FromAction=(int)EnumChangeExperienceValueAction.AnwserToPuzzle,
                    ChangedExperienceValue=DefaultExperienceValueSetting.AddCommentToPuzzle
                };

                db.ExperienceValueHistorys.AddObject(history);

                db.SaveChanges();

                return RedirectToAction("Details", "Puzzle", new { id = puzzleId });
            }
            else if (string.IsNullOrEmpty(anwser))
            {
                return RedirectToAction("Details", new { id = puzzleId });
            }
            
            return View("Index");
            
        }

        //
        // GET: /Puzzle/Edit/5

        public ActionResult Edit(string id = null)
        {
            Post post = db.Posts.Single(p => p.Id == id);
            if (post == null)
            {
                return HttpNotFound();
            }
            return View(post);
        }

        //
        // POST: /Puzzle/Edit/5

        [HttpPost]
        public ActionResult Edit(Post post)
        {
            if (ModelState.IsValid)
            {
                db.Posts.Attach(post);
                db.ObjectStateManager.ChangeObjectState(post, EntityState.Modified);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(post);
        }

        //
        // GET: /Puzzle/Delete/5

        public ActionResult Delete(string id = null)
        {
            Post post = db.Posts.Single(p => p.Id == id);
            if (post == null)
            {
                return HttpNotFound();
            }
            return View(post);
        }

        //
        // POST: /Puzzle/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(string id)
        {
            Post post = db.Posts.Single(p => p.Id == id);
            db.Posts.DeleteObject(post);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}
